package xyz.jfshare.netty.study.client.util;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import xyz.jfshare.netty.study.client.config.Config;
import xyz.jfshare.netty.study.client.pojo.Message;
import xyz.jfshare.netty.study.client.pojo.User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class MenuUtil {

    private static final List<User> friends = new ArrayList<>();
    private static final List<User> notFriends = new ArrayList<>();
    private static final List<Message> systemMsg = new ArrayList<>();
    private static final List<Message> userMsg = new ArrayList<>();
    private static String loginSuccess = "";
    private static String registerSuccess = "";


    public static void MainMenu(Channel channel) throws IOException {
        clear();
        String option = "0";
        do {
            System.out.println("-------------");
            System.out.println("|   1.登录   |");
            System.out.println("|   2.注册   |");
            System.out.println("|   0.退出   |");
            System.out.println("-------------");
            System.out.println("请输入选项: ");
            Scanner input = new Scanner(System.in);
            option = input.nextLine();
            if (option.startsWith("1")){
                LoginMenu(channel);
            }else if (option.startsWith("2")){
                RegisterMenu(channel);
            }else if (option.startsWith("0")){
                break;
            }else {
                System.out.println("请输入正确的选项!");
            }
        }while (true);
        
    }

    private static void LoginMenu(Channel channel) throws IOException {
        clear();
        Scanner input = new Scanner(System.in);
        System.out.println("请输入账号: ");
        String username = input.nextLine();
        System.out.println("请输入密码: ");
        String password = input.nextLine();

        StringBuilder sb = new StringBuilder();
        sb.append(Config.COMMAND_PREFIX);
        sb.append(Config.LOGIN_COMMAND);
        sb.append("username=").append(username);
        sb.append(",password=").append(password);
        String str = sb.toString();

        channel.writeAndFlush(str+"\n");
        System.out.print("正在登录,请稍后");
        try {
            for (int i = 0; i < 3; i++) {
                System.out.print(".");
                Thread.sleep(200);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        clear();
        if (loginSuccess.startsWith("success")){
            loginSuccess = loginSuccess.replace("success-","");
            User user = JSON.parseObject(loginSuccess,User.class);
            successMenu(channel,user);
        }else {
            System.out.println(loginSuccess);
        }
    }

    private static void RegisterMenu(Channel channel){
        clear();
        Scanner input = new Scanner(System.in);
        System.out.println("请输入账号: ");
        String username = input.nextLine();
        System.out.println("请输入密码: ");
        String password = input.nextLine();
        System.out.println("请再次输入密码: ");
        String rePassword = input.nextLine();
        System.out.println("请输入昵称: ");
        String nickName = input.nextLine();
        StringBuilder sb = new StringBuilder();
        sb.append(Config.COMMAND_PREFIX);
        sb.append(Config.REGISTER_COMMAND);
        sb.append("username=").append(username);
        sb.append(",password=").append(password);
        sb.append(",rePassword=").append(rePassword);
        sb.append(",nickName=").append(nickName);
        String str = sb.toString();
        channel.writeAndFlush(str + "\n");

        System.out.print("正在注册,请稍后");
        try {
            for (int i = 0; i < 3; i++) {
                System.out.print(".");
                Thread.sleep(200);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        clear();

        if (registerSuccess.startsWith("success")){
            System.out.println("注册成功,请登录");
        }else {
            System.out.println(registerSuccess);
        }
    }

    private static void clear(){
        for (int i = 0;i<10;i++){
            System.out.println();
        }
    }

    private static void successMenu(Channel channel,User user) throws IOException {
        clear();
        System.out.println("登录成功!");
        String option = "0";
        do {
            systemMsgHandler(channel,user);
            System.out.println("-------------------");
            System.out.println("|   1.进入聊天室   |");
            System.out.println("|   2.单人※聊天   |");
            System.out.println("|   3.添加※好友   |");
            System.out.println("|   0.退※※※出   |");
            System.out.println("-------------------");
            System.out.println("请输入选项: ");
            Scanner input = new Scanner(System.in);
            option = input.nextLine();
            if (option.startsWith("1")){
                chatRoomMenu(channel,user);
            }else if (option.startsWith("2")){
                singleChatMenu(channel,user);
            }else if (option.startsWith("3")){
                addFriendMenu(channel,user);
            }else if (option.startsWith("0")){
                channel.writeAndFlush(Config.COMMAND_PREFIX+Config.LOGOUT_COMMAND+'\n');
                resetInfo();
                break;
            }else {
                clear();
                System.out.println("请输入正确的选项!");
            }
        }while (true);
    }

    //model- [group]:群组  [person]收信人昵称:个人
    private static void sendMessage(Channel channel,String model,User user) throws IOException {
        clear();
        for (Message message : userMsg) {
            System.out.println(message.getContent());
        }
        System.out.println("------------------------");
        System.out.println("输入/?或者--help查看帮助！");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String s = br.readLine();
            s = s.trim();
            if (s.startsWith("/")) {
                if (s.startsWith("/?") || s.startsWith("/？")) {
                    helpMenu();
                }else if(s.startsWith("/bye")) {
                    break;
                }else if(s.startsWith("/q")) {
                    break;
                }else if(s.startsWith("/exit")) {
                    break;
                }else{
                    System.out.println("输入格式有误，请输入/?或--help查看帮助");
                }
            }else if (s.startsWith("--")){
                if (s.startsWith("--help")){
                    helpMenu();
                }else {
                    System.out.println("输入格式有误，请输入/?或--help查看帮助");
                }
            }else {
                if (s.startsWith("quit")) {
                    break;
                }
                if (s.startsWith("exit")) {
                    break;
                }
                String msg = "";
                if (model.startsWith("[group]")){
                    msg = Config.MESSAGE_PREFIX +
                            Config.MESSAGE_GROUP +
                            "nickName=" + user.getNickName() + Config.MESSAGE_REGEX +
                            s +'\n';
                }else if (model.startsWith("[person]")){
                    String to = model.replace("[person]","").trim();
                    msg = Config.MESSAGE_PREFIX +
                            Config.MESSAGE_PERSON +
                            "nickName=" + user.getNickName() + Config.MESSAGE_REGEX +
                            "to=" + to + Config.MESSAGE_REGEX +
                            "id=" + user.getId() + Config.MESSAGE_REGEX +
                            s +'\n';
                }
                channel.writeAndFlush(msg);
            }
        }
        MenuUtil.userMsg.clear();
        channel.writeAndFlush(Config.COMMAND_PREFIX +
                Config.CHOOSE_WINDOW_COMMAND +
                "window=0,"+
                "id=" + user.getId() + '\n');
    }

    private static void chatRoomMenu(Channel channel,User user) throws IOException {
        //向服务端发送选择聊天室模式
        String command = Config.COMMAND_PREFIX + Config.CHOOSE_CHAT_ROOM + user.getNickName();
        channel.writeAndFlush(command + "\n");
        clear();
        System.out.print("欢迎来到聊天室！");
        sendMessage(channel,"[group]",user);
    }

    private static void singleChatMenu(Channel channel,User user) throws IOException {
        MenuUtil.friends.clear();
        //向服务端发送显示好友列表命令
        String command1 = Config.COMMAND_PREFIX + Config.SHOW_FRIEND_COMMAND + "id=" +user.getId();
        channel.writeAndFlush(command1+'\n');
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //向服务端发送选择单人聊天模式
        String command2 = Config.COMMAND_PREFIX + Config.CHOOSE_SINGLE_CHAT+user.getNickName();
        channel.writeAndFlush(command2 + "\n");

        clear();
        if (friends.isEmpty()){
            System.out.println("您暂时没有添加好友");
        }else {
            while (true) {
                System.out.println("请选择聊天的好友");
                for (int i = 1; i <= friends.size(); i++) {
                    User u = friends.get(i - 1);
                    if (u.getStatus().equals(1)) {
                        System.out.printf("%d.", i);
                        System.out.print(u.getNickName() + "\t\t");
                        System.out.println("离线");
                    } else if (u.getStatus().equals(2)) {
                        System.out.printf("%d.", i);
                        System.out.print(u.getNickName() + "\t\t");
                        System.out.println("在线");
                    }
                }
                System.out.println("请输入序号(输0退出):");
                Scanner input = new Scanner(System.in);
                int key = input.nextInt();
                if (key <= 0){
                    MenuUtil.friends.clear();
                    break;
                }
                if (key > friends.size()) {
                    clear();
                    System.out.println("序号输入错误请重新输入");
                    continue;
                }
                //发送选择窗口命令
                channel.writeAndFlush(Config.COMMAND_PREFIX +
                                           Config.CHOOSE_WINDOW_COMMAND +
                                           "window=" + friends.get(key-1).getId()+
                                           ",id=" + user.getId() + '\n');
                //发送获取消息记录命令
                channel.writeAndFlush(Config.COMMAND_PREFIX +
                                           Config.GET_USER_MSG_COMMAND +
                                           "toId=" + friends.get(key-1).getId()+
                                           ",userId=" + user.getId() + '\n');
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sendMessage(channel,"[person]"+friends.get(key - 1).getNickName(),user);
            }
        }
    }

    private static void addFriendMenu(Channel channel,User user){
        MenuUtil.notFriends.clear();
        String command1 = Config.COMMAND_PREFIX + Config.SHOW_NOT_FRIEND_COMMAND + "id=" + user.getId();
        channel.writeAndFlush(command1 + '\n');
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        clear();
        if (notFriends.isEmpty()){
            System.out.println("暂时没有陌生人");
        }else {
            System.out.println("请选择要添加的用户");
            for (int i = 1; i <= notFriends.size(); i++) {
                User u = notFriends.get(i-1);
                if (u.getStatus().equals(1)){
                    System.out.printf("%d.",i);
                    System.out.print(u.getNickName()+"\t\t");
                    System.out.println("离线");
                }else if (u.getStatus().equals(2)){
                    System.out.printf("%d.",i);
                    System.out.print(u.getNickName()+"\t\t");
                    System.out.println("在线");
                }
            }
            System.out.println("请输入序号:(输0退出)");
            Scanner input = new Scanner(System.in);
            int key = input.nextInt();
            if (key <= 0){
                return;
            }
            if (key > notFriends.size()){
                System.out.println("请输入正确的选项！");
                return;
            }
            User choose = notFriends.get(key - 1);
            //用户的昵称
            String nickName = user.getNickName();
            //id为要添加的好友id
            String command2 = Config.COMMAND_PREFIX +
                              Config.ADD_FRIEND_COMMAND +
                              "id=" + choose.getId() + ',' +
                              "nickName=" + nickName;
            channel.writeAndFlush(command2 + '\n');
            System.out.println("请求已发送,等待对方同意");
        }
    }

    private static void helpMenu(){
        clear();
        System.out.println("使用帮助:");
        System.out.println("输入/?或--help查看帮助");
        System.out.println("输入/bye,/quit,/q,/exit退出聊天室或者会话");
    }

    public static void addNotFriends(User user) {
        MenuUtil.notFriends.add(user);
    }

    public static void addFriends(User user) {
        MenuUtil.friends.add(user);
    }

    public static void addSystemMsg(Message message) {
        MenuUtil.systemMsg.add(message);
    }

    public static void addUserMsg(Message message) {
        MenuUtil.userMsg.add(message);
    }

    public static void setLoginSuccess(String loginSuccess) {
        MenuUtil.loginSuccess = loginSuccess;
    }

    public static void setRegisterSuccess(String registerSuccess) {
        MenuUtil.registerSuccess = registerSuccess;
    }

    private static void resetInfo(){
        MenuUtil.registerSuccess = "";
        MenuUtil.loginSuccess = "";
        MenuUtil.friends.clear();
        MenuUtil.notFriends.clear();
        MenuUtil.systemMsg.clear();
        MenuUtil.userMsg.clear();
    }

    private static void systemMsgHandler(Channel channel,User user){
        MenuUtil.systemMsg.clear();
        String command1 = Config.COMMAND_PREFIX + Config.GET_SYSTEM_MSG_COMMAND + user.getId();
        channel.writeAndFlush(command1 + '\n');
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (MenuUtil.systemMsg.isEmpty()){
            return;
        }
        clear();
        Scanner input = new Scanner(System.in);
        for (Message message : systemMsg) {
            String content = message.getContent();

            if (content.startsWith(Config.MESSAGE_CONTENT_FRIEND_APP)){
                content = content.replace(Config.MESSAGE_CONTENT_FRIEND_APP,"");
                Set<String> info = StringUtil.split(content, "-");
                String nickName = "";
                for (String str : info) {
                    if (str.startsWith("昵称:")){
                        nickName = str.replace("昵称:","");
                    }
                }
                System.out.print(content + "\n是否同意(y/n):");
                String key = input.nextLine();
                String command2 = Config.COMMAND_PREFIX +
                        Config.HANDLER_SYSTEM_MSG_COMMAND +
                        "key=" + key.substring(0,1) +
                        ",nickName=" + nickName +
                        ",userId=" + user.getId() +
                        ",message_id=" + message.getId();
                channel.writeAndFlush(command2 + '\n');
            }else if (content.startsWith(Config.MESSAGE_CONTENT_NOT_READ)){
                content = content.replace(Config.MESSAGE_CONTENT_NOT_READ,"");
                System.out.print(content + "\n输入 y 退出:");
                String key = input.nextLine();
                String command2 = Config.COMMAND_PREFIX +
                        Config.HANDLER_SYSTEM_MSG_COMMAND +
                        "key=" + key.substring(0,1) +
                        ",message_id=" + message.getId() ;
                channel.writeAndFlush(command2 + '\n');
            }

        }

    }
}
